package auth

import (
	"com.lh.basic.service/lib/crypto"
	"com.lh.basic.service/lib/tools"
	"com.lh.basic.service/pb/auth"
	"com.lh.data.data/lib/cockroach"
	"com.lh.data.data/lib/redis"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/metadata"
)

func (a *Auth) ResetPassword(ctx context.Context, req *auth.ResetPasswordRequest) (*auth.NoResponse, error) {
	if tools.ValidateToken(ctx) {
		md, _ := metadata.FromIncomingContext(ctx)
		sid := md.Get("sid")[0]
		red := redis.Init()
		val, err := red.GetHRow(fmt.Sprintf("code_%s:1", sid), "code")
		if err != nil {
			return nil, grpc.Errorf(codes.NotFound, "invalid code: %v", err)
		}
		if tools.IsNil(val) && crypto.Same(req.GetCode(), val.(string)) {
			_, _ = red.DelRow(fmt.Sprintf("code_%s:1", sid))
			if crypto.Same(req.GetPassword(), req.GetRePassword()) {
				cry := crypto.Init()
				password, err := cry.PWEncode(req.GetPassword(), cry.Id.String())
				if err != nil {
					return nil, grpc.Errorf(codes.Unauthenticated, "invalid password: %v", err)
				}
				db, err := cockroach.GetDB(ctx)
				if err != nil {
					return nil, grpc.Errorf(codes.Unauthenticated, "failed to connect to database: %v", err)
				}
				id, err := red.GetHRow(fmt.Sprintf("code_%s:2", sid), "uid")
				if tools.IsNil(id) || err != nil {
					return nil, grpc.Errorf(codes.NotFound, "请重新找回密码，用户ID未找到")
				}
				_, err = db.Pool.Exec(db.GetCtx(), "update users.list set password = $1, sign = $2 where id = $3;", password, cry.Id.String(), id.(string))
				if err != nil {
					return nil, err
				}
				return &auth.NoResponse{
					Code:    200,
					Message: "密码重置成功",
					Status:  "ok",
				}, nil
			} else {
				return nil, grpc.Errorf(codes.Unauthenticated, "请检查两次密码是否相同")
			}
		} else {
			return nil, grpc.Errorf(codes.Unauthenticated, "验证码错误")
		}
	}
	return &auth.NoResponse{
		Code: 417,
	}, grpc.Errorf(codes.InvalidArgument, "token验证失败")
}
